package com.djhu.freepartner.web.control;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.djhu.freepartner.bean.PartnerUser;
import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.service.impl.PartnerUserServiceImpl;
import com.djhu.freepartner.utils.DateUtils;
import com.djhu.freepartner.web.entity.enums.Role;
import com.djhu.freepartner.web.service.VerifiyCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Api("用户注册接口")
@RestController
public class RegisterControl {

    private static final List<String> DEFAULT_PORTRAITS = new ArrayList<>();

    @Autowired
    private PartnerUserServiceImpl partnerUserService;

    @Autowired
    private VerifiyCodeService verifiyCodeService;

    @Value("${spring.freepartner.static.url}")
    private String staticUrl ;

    @PostConstruct
    public void init(){
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.png");
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.jpg");
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.jpg");
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.jpg");
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.jpg");
        DEFAULT_PORTRAITS.add("http://"+staticUrl+"/static/image/1.jpg");
    }



    @ApiOperation(value="用户注册", notes="用户注册接口")
    //@VerifiyCodeAnno(name = "register",limit = 10)
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestRsp register(HttpServletRequest servletRequest, @RequestBody JSONObject jsonObject) throws ServiceException {
    //public RestRsp register(@RequestParam(value = "username") String username,@RequestParam(value = "password") String password,@RequestParam(value = "phone") String phone) throws ServiceException {
        //验证传来的用户名 手机号 等等
        //查询用户是否注册
        //进行注册
        //partnerUserService。
//        Map<String, String> parameters = servletRequest.getContentLength()
        String username = jsonObject.getString("username");
        String phone = jsonObject.getString("phone");
        String password = jsonObject.getString("password");
        String clientverifyCode = jsonObject.getString("verifycode");
        String validateCode = jsonObject.getString("validatecode");

        //腾讯信鸽的  token
        String pushtoken = String.valueOf(jsonObject.getOrDefault("pushtoken",""));
        RestRsp restRsp = null;
        boolean isvalidate =  verifiyCodeService.validate(clientverifyCode,validateCode);
        if (isvalidate){
            restRsp = new RestRsp();
            restRsp = new RestRsp("验证码验证失败",Status.VERIFY_CODE_FAIL.getCode());
            return restRsp;
        }
//        RegUtils.match(RegUtils.Regex.of("手机认证",phone,RegUtils.REG_MOBILE),
//                RegUtils.Regex.of("用户名",userName,RegUtils.REG_NAME),
//                RegUtils.Regex.of("登录密码",password,RegUtils.REG_PASS));
        Wrapper<PartnerUser> warper = new EntityWrapper<PartnerUser>().eq("username",username);
        int sum = partnerUserService.selectCount(warper);
        if (sum > 0){
            //用户名已经注册
            throw new ServiceException("用户名已经被注册",Status.ALREADY_EXIST.getCode());
        }
        warper = new EntityWrapper<PartnerUser>().eq("phone",phone);
        sum = partnerUserService.selectCount(warper);
        if (sum > 0){
            //用户名已经注册
            throw new ServiceException("手机号已经被注册",Status.ALREADY_EXIST.getCode());
        }
        PartnerUser user = new PartnerUser();
        user.setBrowseradio(1);
        user.setLoginradio(1);
        user.setBrowseradio(1);
        user.setPushtoken(pushtoken);
        int size = DEFAULT_PORTRAITS.size();
        int index =Math.abs( new Random().nextInt()) % size;
        String portrait = DEFAULT_PORTRAITS.get(index);
        user.setPortrait(portrait);
//        user.setUserid(GeneralUtils.getUUID());
        user.setPassword(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()));
        user.setPhone(phone);
        user.setUsername(username);
        user.setCreatedate(DateUtils.now());
        user.setCreateuser("normal");
        user.setRole(String.valueOf(Role.USER.getRoleCode()));

        boolean isSuccesss = partnerUserService.insert(user);
        if (isSuccesss){
             restRsp = new RestRsp("注册成功",0);
        }else {
             restRsp = new RestRsp("用户注册失败，请重新注册",Status.SERVER_ERROR);
        }
        return restRsp;
    }
}
